package com.rabbitmq.springbootrabbitmq.config;

import com.rabbitmq.client.Return;
import com.rabbitmq.client.ReturnCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    //注入
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //注入
    @PostConstruct//在其他方法编译之后执行
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String id = correlationData != null ? correlationData.getId() : "";
        /**
         * 交换机确认回调方法
         * 1.发消息，交换机收到了
         *  1.1correlationData保存回调消息的ID及相关消息
         *  1.2交换机收到雄安下 ack = true
         *  1.3cause null
         * 2 发消息 交换机接收失败
         *  2.1correlationData保存回调消息的ID及相关消息
         *  2.2交换机接收到消息 ack = false
         *  2.3cause失败的原因
         */
        if (b){
            log.info("交换机收到了Id为：{}的消息",id);
        } else {
            log.info("交换机未接收到id为：{}的消息，由于原因{}",id,s);
        }
    }


    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("消息被退回了：{},路由为",returnedMessage.getMessage(),returnedMessage.getRoutingKey());
    }
}
